package com.obrock;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.*;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.CompoundButton.OnCheckedChangeListener;

import java.util.List;

/**
 * @author Rick
 */
public class EditAccount extends Activity implements OnCheckedChangeListener, EditAnalytics.EditAnalyticsListener {

    static final int DIALOG_DATE = 21;
    static final int ANALYTICS_ADD = 23;
    static final int ANALYTICS_EDIT = 24;
    TextView title;
    TextView amountTitle;
    Button btnOK;
    Button btnDate;
    Button btnEditAnalytics;
    Button btnAddAnalytics;
    TextView datePlace;
    EditText name;
    Spinner type;
    EditText amount;
    EditText remark;
    LinearLayout container;
    Account account;
    List<Analytics> analytics;
    boolean editMode;
    Context context;
    Analytics selected;

    TableLayout blockHeader;

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.edit_account);

        context = this;

        title = (TextView) findViewById(R.id.title);
        amountTitle = (TextView) findViewById(R.id.amount_title);
        btnOK = (Button) findViewById(R.id.btnOk);
        btnEditAnalytics = (Button) findViewById(R.id.btnEditAnalytics);
        btnAddAnalytics = (Button) findViewById(R.id.btnAddAnalytics);
        btnDate = (Button) findViewById(R.id.btnDate);
        container = (LinearLayout) findViewById(R.id.container);
        blockHeader = (TableLayout) findViewById(R.id.block_header);


        name = (EditText) findViewById(R.id.name);
        type = (Spinner) findViewById(R.id.type);
        datePlace = (TextView) findViewById(R.id.date_place);
        amount = (EditText) findViewById(R.id.amount);
        amount.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if (b) {
                    if (Main.eval(amount.getText().toString(), 0.0) == 0) {
                        amount.setText("");
                    }
                }
            }
        });
        amount.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (charSequence.toString().contains("=") || charSequence.toString().contains("\n")) {
                    double sum = account.balance;
                    amount.setText(String.format("%.2f", Main.eval(charSequence.toString(), sum)));
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {
            }
        });


        remark = (EditText) findViewById(R.id.remark);

        name.setInputType(name.getInputType() | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES);
        remark.setInputType(name.getInputType() | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES);

        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
                R.array.account_types, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        type.setAdapter(adapter);

        btnOK.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                Intent intent = new Intent();
                account.name = name.getText().toString();
                account.remark = remark.getText().toString();
                try {
                    String a = amount.getText().toString();
                    double sum = account.balance;
                    account.amount = Main.eval(a, sum);
                } catch (Exception e) {
                    account.amount = 0.0;
                }

                //account.amount = Double.parseDouble(amount.getText().toString().replace(" ", "").replace(",", "."));
                intent.putExtra("account", account);
                setResult(RESULT_OK, intent);
                finish();
            }
        });

        btnDate.setOnClickListener(new OnClickListener() {

            public void onClick(View arg0) {
                showDialog(DIALOG_DATE);
            }
        });

        btnEditAnalytics.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                showAnalytics(!editMode);
            }
        });

        btnAddAnalytics.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                new EditAnalytics(Main.db, -1, null).show(getFragmentManager(), "fragment_edit_analytics");
                /*
                Intent inent = new Intent(context, EditAnalytics.class);
                inent.putExtra("parentID", -1);
                startActivityForResult(inent, ANALYTICS_ADD);
                */
            }
        });


        type.setOnItemSelectedListener(new OnItemSelectedListener() {

            public void onItemSelected(AdapterView<?> arg0, View arg1, int index, long arg3) {
                account.type = index;
                switch (index) {
                    case Account.TYPE_NORMAL:
                        amountTitle.setText(getResources().getString(R.string.account_amount_start));
                        break;
                    case Account.TYPE_DEBT:
                        amountTitle.setText(getResources().getString(R.string.account_amount_debt));
                        break;
                    case Account.TYPE_CARD:
                        amountTitle.setText(getResources().getString(R.string.account_amount_limit));
                        break;
                }
            }

            public void onNothingSelected(AdapterView<?> arg0) {
                //account.type = Account.TYPE_NORMAL;
            }
        });


        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            //account = new Account(extras.getLong("accountID", -1));
            account = (Account) extras.getSerializable("account");
        }

        if (account == null) {
            account = new Account(Main.db);
        }

        name.setText(account.name);
        type.setSelection(account.type);
        amount.setText(String.format("%.2f", account.amount));

        remark.setText(account.remark);
        datePlace.setText(Main.dateFullString(account.date));

        /*
        name.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if(b) {
                    blockHeader.setVisibility(View.GONE);
                } else {
                    blockHeader.setVisibility(View.VISIBLE);
                }
            }
        });
        remark.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if(b) {
                    blockHeader.setVisibility(View.GONE);
                } else {
                    blockHeader.setVisibility(View.VISIBLE);
                }
            }
        });
        amount.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if(b) {
                    amount.selectAll();
                    blockHeader.setVisibility(View.GONE);
                } else {
                    blockHeader.setVisibility(View.VISIBLE);
                }
            }
        });
        */


        showAnalytics(false);
    }

    /*
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data == null) {
            return;
        }

        switch (requestCode) {
            case ANALYTICS_ADD:
                if (resultCode == RESULT_OK) {
                    Analytics a = (Analytics) data.getSerializableExtra("analytics");
                    a.append();
                    account.linkVirtual(a);
                    //account.refresh();
                    showAnalytics(editMode);
                    Toast.makeText(getBaseContext(), getResources().getString(R.string.msg_analytics_added), Toast.LENGTH_SHORT).show();
                }
                break;
            case ANALYTICS_EDIT:
                if (resultCode == RESULT_OK) {
                    Analytics a = (Analytics) data.getSerializableExtra("analytics");
                    a.update();
                    //account.refresh();
                    showAnalytics(editMode);
                    Toast.makeText(getBaseContext(), getResources().getString(R.string.msg_analytics_changed), Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }
    */

    void showAnalytics(boolean mode) {
        editMode = mode;
        if (!editMode) {
            //btnAddAnalytics.setVisibility(View.GONE);
            container.removeAllViews();
            analytics = account.analytics;
            for (int i = 0; i < analytics.size(); ++i) {
                TextView x = new TextView(this);
                x.setId(i);
                x.setText(analytics.get(i).name);
                x.setTextColor(getResources().getColor(R.color.list_color));
                selected = analytics.get(i);
                x.setOnLongClickListener(new View.OnLongClickListener() {
                    Analytics root = selected;

                    @Override
                    public boolean onLongClick(View view) {
                        selected = root;
                        return false;
                    }
                });
                registerForContextMenu(x);
                container.addView(x);
            }
        } else {
            //btnAddAnalytics.setVisibility(View.VISIBLE);

            container.removeAllViews();
            analytics = Main.db.getAnalyticsList(account);
            for (int i = 0; i < analytics.size(); ++i) {
                CheckBox x = new CheckBox(this);
                x.setId(i);
                x.setText(analytics.get(i).name);
                x.setTextColor(getResources().getColor(R.color.list_color));
                x.setChecked(analytics.get(i).selected);
                x.setOnCheckedChangeListener(this);
                selected = analytics.get(i);
                x.setOnLongClickListener(new View.OnLongClickListener() {
                    Analytics root = selected;

                    @Override
                    public boolean onLongClick(View view) {
                        selected = root;
                        return false;
                    }
                });
                registerForContextMenu(x);
                container.addView(x);
            }
        }
    }

    /*
    public void onClick(View v) {
    Intent inent = new Intent(context, EditAnalytics.class);
    inent.putExtra("analyticsID", -1);
    inent.putExtra("analytics", analytics.get(v.getId()));
    startActivityForResult(inent, ANALYTICS_EDIT);
    }
     * 
     */
    public void onCheckedChanged(CompoundButton v, boolean on) {
        if (on) {
            account.linkVirtual(analytics.get(v.getId()));
        } else {
            account.unlinkVirtual(analytics.get(v.getId()));
        }
        //account.refresh();

    }

    @Override
    protected Dialog onCreateDialog(int id) {
        if (id == DIALOG_DATE) {
            DatePickerDialog tpd = new DatePickerDialog(this,
                    myCallBack,
                    account.date.getYear() + 1900,
                    account.date.getMonth(),
                    account.date.getDate());
            return tpd;
        }
        return super.onCreateDialog(id);
    }

    DatePickerDialog.OnDateSetListener myCallBack = new DatePickerDialog.OnDateSetListener() {

        public void onDateSet(DatePicker view, int year, int monthOfYear,
                              int dayOfMonth) {

            account.date.setYear(year - 1900);
            account.date.setMonth(monthOfYear);
            account.date.setDate(dayOfMonth);

            datePlace.setText(Main.dateFullString(account.date));
        }
    };

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {

        menu.setHeaderTitle(getResources().getString(R.string.analytics));
        super.onCreateContextMenu(menu, v, menuInfo);
        MenuInflater inflater = new MenuInflater(this);
        inflater.inflate(R.menu.analytics, menu);
        selected = analytics.get(v.getId());
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {

        switch (item.getItemId()) {
            case R.id.create:
                new EditAnalytics(Main.db, -1, null).show(getFragmentManager(), "fragment_edit_analytics");
                return true;

            case R.id.edit: {
                new EditAnalytics(Main.db, -1, selected).show(getFragmentManager(), "fragment_edit_analytics");
                return true;
            }

            case R.id.delete: {
                selected.delete();
                account.refresh();
                showAnalytics(editMode);
                Toast.makeText(getBaseContext(), getResources().getString(R.string.msg_analytics_deleted), Toast.LENGTH_SHORT).show();
                return true;
            }
            default:
                return super.onContextItemSelected(item);
        }
    }

    @Override
    public boolean onUpdateAnalytics(Analytics analytics) {
        analytics.update();
        //account.refresh();
        showAnalytics(editMode);
        Toast.makeText(getBaseContext(), getResources().getString(R.string.msg_analytics_changed), Toast.LENGTH_SHORT).show();
        return true;
    }

    @Override
    public boolean onAppendAnalytics(Analytics analytics) {
        analytics.append();
        account.linkVirtual(analytics);
        //account.refresh();
        showAnalytics(editMode);
        Toast.makeText(getBaseContext(), getResources().getString(R.string.msg_analytics_added), Toast.LENGTH_SHORT).show();
        return true;
    }

    @Override
    public boolean onDeleteAnalytics(Analytics analytics) {
        selected.delete();
        account.refresh();
        showAnalytics(editMode);
        Toast.makeText(getBaseContext(), getResources().getString(R.string.msg_analytics_deleted), Toast.LENGTH_SHORT).show();
        return true;
    }
}
